package analyse.database.utility;

import java.net.URL;
import java.util.Properties;

import org.apache.log4j.Logger;


public class PropertyReader {
	
	private static Logger log = Logger.getLogger(ReflectionUtility.class);
	
	private static PropertyReader instance = null;
	private Properties properties = null;
	
	private PropertyReader() {
		properties = new Properties();
		try {
			URL url = Utility.getResource(PropertyReader.class, "analyse.properties");
			if (url != null) {
				properties.load(url.openStream());
				log.info("read analyse properties");
			} else {
				log.error("analyse.properties not found");
			}
			
			
		} catch (Exception e) {
			log.error("Error during reading analyse properties", e);
		}		
	}
	
	
	public static PropertyReader getInstance() {
		
		if (instance == null) {
			synchronized (PropertyReader.class) {
				instance = new PropertyReader();
			}
		}
		return instance;
	}
	
	public String getValueAsString(String key, String defaultValue) {
		String result = defaultValue;
		if (key != null) {
			if (properties.get(key) != null) {
				result = properties.get(key).toString();
			}
			if (key.toLowerCase().indexOf("password") > 0
					|| key.toLowerCase().indexOf("pwd") > 0
					|| key.toLowerCase().indexOf("passwort") > 0) {
				log.debug("[Key: " + key + " - Value: *****]");
			} else {
				log.debug("[Key: " + key + " - Value: " + result +"]");
			}
			
		}
		return result;
	}
	
	public boolean getValueAsBoolean(String key, boolean defaultValue) {
		boolean result = defaultValue;
		String stringValue = getValueAsString(key, null);
		if (stringValue != null
				&& stringValue.equalsIgnoreCase("true")){
			result = true;
		}
		return result;
	}
	
	public int getValueAsInt(String key, int defaultValue) {
		int result = defaultValue;
		String stringValue = getValueAsString(key, null);
		if (stringValue != null) {
			try {
				result = Integer.parseInt(stringValue);
			} catch (NumberFormatException e) {
				log.error("", e);
			}
		}
		return result;
	}
}
